<?php
/**
 * 景点接口数据转存
 */
namespace app\common\model;

use think\Model;
use app\common\server\Tour;
use think\helper\Str;

class ScenicsLoad extends Model
{
    /**
     * 同步全部
     * 
     * @return int  更新的条数
     */
    public function syncAll()
    {
        $data = $this->_getAllScenics();
        $count = 0;
        foreach ($data as $item) {
            $item = static::_formatToTable($item);
            $item['img_path'] = $item['img_path'][0];
            $find = $this->where(['munit_id'=>$item['munit_id'], 'price_type_id'=>$item['price_type_id']])->value('id');
            if ($find) {
                unset($item['munit_id']);
                $res = $this->allowField(true)->data($item, true)->save($item, ['id'=>$find]);
                if ($res) {
                    $count ++;
                }
            } else {
                $this->allowField(true)->data($item, true)->isUpdate(false)->save();
                $count ++;
            }
        }
        return $count;
    }

    /**
     * 同步一条数据
     * 
     * @param  int   $id
     * @return int   是否有更新
     */
    public function sync($id)
    {
        $query = $this->field('munit_id,price_type_id')->find($id);
        if ($query) {
            $fetch = Tour::instance()->scenicView($query['munit_id']);
            $fetch = json_decode($fetch, true);
            if ($fetch['success']) {
                $data = static::_formatToTable($fetch['data']);
                unset($data['munit_id']);
                unset($data['price_type_id']);
                return $this->allowField(true)->save($data, ['id'=>$id]);
            }
        }
        return 0;
    }

    /**
     * 字段映射转换
     * 
     * @param  array  $item 接口返回值
     * @return array       字段名转下划线，以匹配数据库
     */
    private static function _formatToTable($item)
    {
        $res = [];
        foreach ($item as $field => $value) {
            $res[Str::snake($field)] = $value;
        }
        return $res;
    }

    /**
     * 接口获取全部景点数据 
     * 
     * @return array
     */
    private function _getAllScenics()
    {
        $data = [];
        $server = Tour::instance();
        while (true) {
            $temp = $server->scenicLists();
            $temp = json_decode($temp, true);
            if (! $temp['success']) {
                break;
            }
            $data = array_merge($data, $temp['data']['pageData']);
            if ($temp['data']['pageNumber'] == $temp['data']['totalPages']) {
                break;
            }
        }
        return $data;
    }
}